let mysql = require('mysql');
//let poolCluster;
module.exports = config => {
    let poolCluster = mysql.createPoolCluster(config.poolClusterConfig || {
        restoreNodeTimeout: 5000,
        defaultSelector: "RR"
    });
    poolCluster.on('remove', function(nodeId) {
        console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1
    });

    config.nodes.forEach(element => {
        // console.log(element);
        poolCluster.add(element);
    });

    console.log({ message: "Mysql poolCluster inited", nodes: poolCluster._nodes });

    return {

        query: function(sql, paras, callback) {
            poolCluster.getConnection((err, conn) => {
                if (err) {
                    // console.log(err);
                    callback(err);
                } else {
                    // console.log({ id: conn.threadId })
                    conn.query(sql, paras, (err, results, fields) => {
                        conn.release();
                        callback(err, results, fields);
                    });
                }
            });
        },

        queryPromise: function(sql, paras) {
            return new Promise((resolve, reject) => {
                this.query(sql, paras, (err, results, fields) => {
                    if (err) reject({ err, sql, paras, results })
                    else resolve(results);
                });
            })
        },

        // callback(err,conn);
        beginTransaction: function(callback) {
            poolCluster.of('*').getConnection((err, conn) => {
                if (err) callback(err)
                else conn.beginTransaction(err => {
                    if (err) callback(err)
                    else callback(err, conn);
                })
            })
        },

        beginTransactionPromise: function() {
            return new Promise((resolve, reject) => {
                this.beginTransaction((err, conn) => {
                    if (err) reject(err)
                    else {
                        conn.queryPromise = function(sql, paras) {
                            return new Promise((resolve, reject) => {
                                conn.query(sql, paras, (err, results, fields) => {
                                    if (err) reject({ err, sql, paras, results })
                                    else resolve(results);
                                })
                            })
                        };
                        conn.commitPromise = function() {
                            return new Promise((resolve, reject) => {
                                conn.commit(err => {
                                    if (err) reject(err)
                                    else resolve()
                                })
                            })
                        }
                        resolve(conn);
                    }
                });
            })
        }
    }
}